const app = getApp();
import {
  ordedownload,
  orderInfo,
  getOrderReturnAddress,
  orderReturnAddExpress,
  orderApplyReturn,
  getReturnExpressList,
  orderReturnCancel,
  orderPreAuth,
  getRenewalGoodsStatus,
  orderBuyDeposit
} from "../../../api/order";
import {
  getBtnsByStatus,
  cancelOrder,
  cancelRefundApply,
  confirmReceipt,
  payFirstRent
} from "../../../utils/order";
import {
  disposeData
} from "../../../utils/outData";
import {
  baseImgUrl,
  baseUrl
} from "../../../setting";

import {
  createPreAuth,
  createContract,
  createHuabei
} from "../../../api/index";
Page({
  data: {
    orderTip: '',
    order_id: '',
    goodsData: {},
    btns: [],
    showMore: true,
    showService: false,
    returnAddress: {},
    addressModal: false,
    addressBtn: [{
        text: '取消',
        extClass: 'button1'
      },
      {
        text: '复制地址',
        extClass: 'button2'
      },
    ],
    addressOneBtn: [{
      text: '返回',
      extClass: 'button1'
    }, ],
    returnModal: false,
    returnBtn: [{
        text: '取消',
        extClass: 'button1'
      },
      {
        text: '确认归还',
        extClass: 'button2'
      },
    ],
    returnApplyBtn: [{
        text: '取消申请',
        extClass: 'button1'
      },
      {
        text: '确认申请',
        extClass: 'button2'
      },
    ],
    order_id: '',
    status: 0,
    flowModal: false,
    flowList: [],
    flowIndex: -1,
    flowNo: '',
    placeholder: '请填写物流单号',
    disabledInput: false,
    typetime: false,
    isShow: true
  },
  closeService() {
    this.setData({
      showService: false
    })
  },
  onLoad(options) {
    this.setData({
      order_id: options.id || disposeData().id,
      typetime: options.typetime || true
    })

  },
  tap(){
    console.log(554454);
  },
  onShow() {
    let typeTime = this.data.typetime
    if (typeTime = true) {
      setTimeout(() => {
        this.getData();
      }, 1500)
    } else {
      this.getData();
    }
  },
  goToBill(e) {
    const order_id = e.currentTarget.dataset.id;
    my.navigateTo({
      url: '../../bill/bill?order_id=' + order_id + '&isView=' + true
    });
  },
  toSnapshot(e) {
    const {
      goodsId,
      orderId
    } = e.currentTarget.dataset
    my.navigateTo({
      url: '../../orderSnapshot/orderSnapshot?goodsId=' + goodsId + '&orderId=' + orderId
    })
  },
  onReletClick() {
    const {
      goodsId,
      setmealId,
      goodsStatus,
      order_id
    } = this.data
    if (!goodsStatus) {
      this.setData({
        reletModal: false,
        goodsStatus: ''
      })
    } else {
      my.navigateTo({
        url: "../../productDetails/productDetails?goodsId=" + goodsId + '&setmealId=' + setmealId + '&is_renewal=' + 1 + '&parent_order_id=' + order_id
      })
    }
  },
  checkProtocol() {
    const orderid = this.data.order_id
    if (!this.data.goodsData || !this.data.goodsData.pact_url) {
      my.showToast({
        type: 'none',
        content: '还未签署协议',
        duration: 2000
      });
      return;
    }
    my.showLoading({
      content: '正在下载协议...'
    });
    // my.downloadFile({
    //   url: baseImgUrl + this.data.goodsData.pact_url,
    //   success({ apFilePath }) {
    //     my.hideLoading();
    //     my.openDocument({
    //       filePath: apFilePath,
    //       fileType: 'pdf',
    //       success: (res) => {
    //         console.log('open document success')
    //       }
    //     })
    //   }
    // })
    my.downloadFile({
      url: baseImgUrl+this.data.goodsData.pact_url ,
      success({
        apFilePath
      }) {
        my.hideLoading();
        my.openDocument({
          filePath: apFilePath,
          fileType: 'pdf',
          success: (res) => {
            console.log('open document success')
          }
        })
      }
    })
    // ordedownload(orderid).then((res) => {
    //   my.downloadFile({
    //     url: res,
    //     success({
    //       apFilePath
    //     }) {
    //       my.hideLoading();
    //       my.openDocument({
    //         filePath: apFilePath,
    //         fileType: 'pdf',
    //         success: (res) => {
    //           console.log('open document success')
    //         }
    //       })
    //     }
    //   })
    // })

  },
  checkOldOrder() {
    if (getCurrentPages().length === 5) {
      my.redirectTo({
        url: './orderpay?id=' + this.data.goodsData.parent_order_id
      });
    } else {
      my.navigateTo({
        url: './orderpay?id=' + this.data.goodsData.parent_order_id
      })
    }
  },
  checkReletOrder() {
    if (getCurrentPages().length === 5) {
      my.redirectTo({
        url: './orderpay?id=' + this.data.goodsData.sub_order_id
      });
    } else {
      my.navigateTo({
        url: './orderpay?id=' + this.data.goodsData.sub_order_id
      })
    }
  },
  getOrderTip(status) {
    switch (status) {
      case 2:
        this.setData({
          orderTip: '预计两个小时后自动关闭订单，请及时处理'
        });
        break;
      case 10:
        this.setData({
          orderTip: '审核发货预计需要3个工作日，请保持手机畅通'
        });
        break;
      case 11:
        this.setData({
          orderTip: '审核退款预计1—3个工作日，请保持手机畅通'
        });
        break;
      case 20:
        this.setData({
          orderTip: '您的订单已发货，请及时收货'
        });
        break;
      case 1:
        this.setData({
          orderTip: '您的订单已取消'
        });
        break;
      case 60:
        this.setData({
          orderTip: '您的订单已完成'
        });
        break;
      case 30:
        const {
          lease_time, month_total
        } = this.data.goodsData;
        const tip = '您的订单租期：' + lease_time + '（共' + month_total + '月）到期后请及时处理（归还、续租、买断）';
        this.setData({
          orderTip: tip
        });
        break;
      case 13:
        this.setData({
          orderTip: '商家拒绝退款，拒绝原因：'
        });
        break;
      case 16:
        const {
          setmeal_foregift, pay_type
        } = this.data.goodsData;
        this.setData({
          orderTip: '您的订单已退款' + (pay_type == 2 ? '，已退回冻结押金￥' + setmeal_foregift : '')
        })
        break;
      case 41:
        this.setData({
          orderTip: '您已申请归还，请主动联系商家进行处理，商家会在3个工作日内确认是否同意归还。'
        })
        break;
      case 42:
        this.setData({
          orderTip: '商家已同意归还，请填写归还物流信息'
        })
        break;
      case 44:
        this.setData({
          orderTip: '您已发货，等待商家收货'
        })
        break;
      case 45:
        this.setData({
          orderTip: '商家已确认收货'
        })
        break;
      case 43:
        this.setData({
          orderTip: '商家未同意归还，请联系商家'
        })
        break;
      case 62:
        const {
          buyout_amount
        } = this.data.goodsData;
        this.setData({
          orderTip: '实付买断金额：￥' + buyout_amount
        });
        break;

      default:
        break;
    }
  },
  getData() {
    let that = this
    orderInfo(this.data.order_id).then(res => {
      my.stopPullDownRefresh();
      const btns = getBtnsByStatus(res).filter(item => item.id != 9);
      switch (res.is_authentic) {
        case 0:
          if (res.status == 1) {
            that.setData({
              isShow: true
            })
          } else {
            that.setData({
              isShow: false
            })
          }
          break;
        case 1:
          if (res.status) {
            that.setData({
              isShow: true
            })
          }
          break;
          default:
            res.display=true
            break; 
      }

      this.setData({
        goodsData: res || {},
        btns
      })
      this.getOrderTip(this.data.goodsData.status);
    }).catch(err => {
      my.stopPullDownRefresh();
    })

  },

  goToShop() {

    // my.navigateTo({
    //   url: '../../storeDetails/storeDetails?member_id=' + this.data.goodsData.member_id
    // });
    my.navigateTo({
      url: '../../storeDetails/storeDetails?member_id=' + this.data.goodsData.member_id + "&shopname=" + this.data.goodsData.shopname
    });
  },
  copyOrderNum() {
    my.setClipboard({
      text: this.data.goodsData.trade_no,
      success: () => {
        my.alert({
          content: '已复制',
          buttonText: '我知道了'
        })
      }
    });
  },
  clickMore() {
    this.setData({
      showMore: !this.data.showMore
    })
  },
  btnClick(e) {
    this.setData({
      showMore: false
    });
    const that = this;
    const {
      id,
      status,
      order_id,
      isAuth,
      pay_type,
      esignUserId,
      flowId,
      sign_status,
      goods_id,
      contract_type
    } = e.currentTarget.dataset;
    this.setData({
      order_id,
      status
    })

    if (id == 2) {
      cancelOrder(order_id, function () {
        that.getData();
      })
    }
    if (id == 9) {
      my.navigateTo({
        url: '../../applyRefund/applyRefund?order_id=' + order_id
      });
    }
    if (id == 18) {
      cancelRefundApply(order_id, function () {
        that.getData();
      })
    }
    if (id == 3 && status == 20) {
      confirmReceipt(order_id, function () {
        that.getData();
      })
    }
    if ((id == 6 && status == 44) || id == 19) {
      my.navigateTo({
        url: '../../logistics/logistics?order_id=' + order_id
      });
    }
    if (id == 4) {
      my.navigateTo({
        url: '../../bill/bill?order_id=' + order_id
      });
    }
    console.log(id, status, sign_status)
    // debugger
    if ((id == 1 || id == 20) && (status == 2 || sign_status !== 2)) {
      // my.navigateTo({
      //   url: '../../authentication/authentication?orderId=' + order_id + '&payType=' + pay_type + '&isAuth=' + isAuth + '&esignUserId=' + esignUserId + '&flowId=' + flowId + '&status=' + status + '&contractType=' + contract_type + '&signStatus' + sign_status
      // });

      this.isContract()
    }
    if ((id == 1 || id == 20) && (status == 2 && sign_status == 2)) {
      // my.navigateTo({
      //   url: '../../authentication/authentication?orderId=' + order_id + '&payType=' + pay_type + '&isAuth=' + isAuth + '&esignUserId=' + esignUserId + '&flowId=' + flowId + '&status=' + status + '&contractType=' + contract_type + '&signStatus' + sign_status
      // });

      this.createAuth()
    }
    if ((id == 1 || id == 20) && (status == 3 && sign_status == 2)) {
      my.navigateTo({
        url: '../../bill/bill?order_id=' + order_id
      })
    }
    if (id == 17) {
      this.setData({
        showService: true
      })
    }
    if (id == 7) {
      my.navigateTo({
        url: '../../productDetails/productDetails?goodsId=' + goods_id
      });
    }
    if (id == 14) {
      my.navigateTo({
        url: '../../buyout/buyout?orderId=' + order_id
      });
    }
    // 立即归还
    if (id == 11) {
      if (status == 40) {
        this.setData({
          returnModal: true
        })
      } else if (status == 42) {
        getReturnExpressList().then(res => {
          that.setData({
            returnModal: false,
            flowModal: true,
            flowList: res
          });
        })
      }
    }
    // 获取归还地址
    if (id == 16) {
      getOrderReturnAddress(order_id).then(res => {
        if (res) {
          this.setData({
            returnAddress: res,
            addressModal: true
          })
        }
      }).catch(err => {
        this.setData({
          addressModal: false
        })
      })
    }
    // 取消归还
    if (id == 5) {
      orderReturnCancel(order_id).then(res => {
        my.showToast({
          type: 'none',
          content: '操作成功',
          duration: 1000,
        });
        that.getData();
      })
    }
    // 申请归还
    if (id == 10) {
      this.setData({
        returnModal: true
      })
    }
    // 再次申请
    if (id == 12) {
      orderApplyReturn(order_id).then(res => {
        that.getData();
      })
    }
    // 重新签约
    if (id == 22) {
      that.againPreAuth();
    }
    // 申请续租
    if (id == 15) {
      getRenewalGoodsStatus(order_id).then(res => {
        const {
          goods_id,
          setmeal_id,
          status
        } = res
        if (status == 1) {
          this.setData({
            reletModal: true,
            goodsStatus: status,
            goodsId: goods_id,
            setmealId: setmeal_id
          })
        } else {
          this.setData({
            reletModal: true,
            goodsStatus: '',
          })
        }
      }).catch(err => {
        this.setData({
          reletModal: false,
          goodsStatus: '',
        })
      })
    }
  },
  // 签约预授权
  againPreAuth() {
    const that = this
    orderPreAuth(that.data.order_id).then(res => {
      if (res.orderStr) {
        my.tradePay({
          orderStr: res.orderStr,
          success: (res) => {
            that.getData();
          },
          fail: (res) => {
            my.showToast({
              type: 'fail',
              content: '签约失败，请稍后重试',
              duration: 1000,
            });
          }
        });
      }
    })
  },
  onAddressClick(e) {
    let index = e.target.dataset.index
    if (index == 0) {
      this.setData({
        addressModal: false,
      });
    } else {
      my.setClipboard({
        text: this.data.returnAddress,
        success: () => {
          my.showToast({
            type: 'none',
            content: '复制成功',
            duration: 1000,
          });
        }
      });
    }
  },
  onReturnClick(e) {
    const that = this
    let index = e.target.dataset.index
    if (index == 0) {
      that.setData({
        returnModal: false,
      });
    } else {
      const {
        order_id,
        status
      } = that.data
      if (status == 40) {
        getReturnExpressList().then(res => {
          that.setData({
            returnModal: false,
            flowModal: true,
            flowList: res
          });
        })
      } else if (status == 30 || status == 39) {
        orderApplyReturn(order_id).then(res => {
          that.getData();
          that.setData({
            returnModal: false
          });
        })
      }
    }
  },
  bindPickerChange(e) {
    this.setData({
      flowIndex: e.detail.value,
      disabledInput: e.detail.value == 0 ? true : false,
      placeholder: e.detail.value == 0 ? '无需填写单号' : '请填写物流单号',
    });
  },
  onFlowNo(e) {
    let reg = /^[0-9A-Za-z]+$/
    console.log(reg.test(e.detail.value))
    if (!reg.test(e.detail.value)) {
      my.showToast({
        type: 'none',
        content: '请填写正确的物流单号',
        duration: 1500,
      });
    }
    this.setData({
      flowNo: e.detail.value
    })
  },
  toAddFlow() {
    const that = this
    const {
      order_id,
      flowIndex,
      flowNo,
      flowList
    } = that.data
    const reg = /^[0-9A-Za-z]+$/
    if (flowIndex < 0) {
      my.showToast({
        type: 'none',
        content: '请选择物流名称',
        duration: 1500,
      });
      return false
    }
    if (!flowNo && flowIndex > 0) {
      my.showToast({
        type: 'none',
        content: '请填写物流单号',
        duration: 1500,
      });
      return false
    }
    if (flowNo && !reg.test(flowNo)) {
      my.showToast({
        type: 'none',
        content: '请填写正确的物流单号',
        duration: 1500,
      });
      return false
    }
    orderReturnAddExpress({
      order_id,
      logistics_name: flowList[flowIndex].name,
      logistics_no: flowNo,
    }).then(res => {
      this.setData({
        flowModal: false
      });
      that.getData();
    })
  },
  closeModal() {
    this.setData({
      flowModal: false
    })
  },
  onPullDownRefresh() {
    this.getData();
  },
  isContract() {
    const that = this
    const {
      order_id
    } = that.data.goodsData
    //sml prod
    const env = 'prod'
    my.showLoading({
      content: '正在跳转合同...'
    });
    createContract(order_id).then(res => {
      console.log('调起合同', res)
      if (res.flowId) {
        my.hideLoading({
          page: that
        });
        my.setStorage({
          key: 'hasCreateSign',
          data: true
        });
        const {
          flowId,
          signerId
        } = res
        console.log('走到合同签名');
        my.ap.openURL({
          url: `${baseUrl}/2.html?openUrl=${res.contractUrl}&orderid=${order_id}`, // 请将 url 替换为有效的页面地址
          success: (res) => {
            my.redirectTo({
              url: `pages/user/orderpay?id=${orderId}&typetime=${true}`,
            });
          
          },
          fail: (err) => {
            console.log('openURL success', err)
          }
        });
      } else {}
    })
  },
  createAuth() {
    const that = this;
    const {
      order_id,
      pay_type
    } = that.data.goodsData
    if (pay_type == 2) {
      createPreAuth(order_id).then(res => {
        if (res.orderStr) {
          console.log('支付');
          my.tradePay({
            orderStr: res.orderStr,
            success: (res) => {
              if (res.resultCode == 9000) {
               that.isContract()
              } else {
                my.showToast({
                  type: 'fail',
                  content: '支付未完成',
                  duration: 1000,
                });
              }
            },
            fail: (res) => {
              my.showToast({
                type: 'fail',
                content: '支付失败，请稍后重试',
                duration: 1000,
              });
            }
          });
        } else {
          that.getData()
        }
      })
    } else if (pay_type == 3) {
      createHuabei(order_id).then(res => {
        // console.log('花呗支付', res)
        if (res.trade_no) {
          my.tradePay({
            tradeNO: res.trade_no,
            success: (res) => {
              let data = JSON.parse(JSON.stringify(res))
              // console.log('data',data)
              if (data.resultCode == 9000) {
                that.getData()
              } else {
                my.showToast({
                  type: 'fail',
                  content: '支付失败，请稍后重试',
                  duration: 1000,
                });
              }
            }
          });
        } else {
          if (res.sign_status == 0) {
            that.isContract()
          } else if (res.sign_status == 1) {
            my.confirm({
              title: '提示',
              content: '继续签署合同?',
              confirmButtonText: '是,继续',
              cancelButtonText: '否,回首页',
              success: info => {
                if (info.confirm) {
                  my.showLoading({
                    content: '正在跳转合同...'
                  });
                  setTimeout(() => {
                    my.hideLoading()
                  }, 800);
                  my.setStorage({
                    key: 'hasCreateSign',
                    data: true
                  });
                  my.navigateTo({
                    url: `plugin://esign/esign?env=${'prod'}&flowId=${res.flow_id}&signerId=${res.esign_user_id}`,
                  })
                } else {
                  my.switchTab({
                    url: '../../index/index'
                  })
                }
              },
            });
          } else {
            my.showLoading({
              content: '合同已签署完成...'
            });
            setTimeout(() => {
              my.hideLoading()
            }, 1000);
            my.reLaunch({
              url: '../success/success'
            })
          }
        }
      })
    } else if (pay_type == 1) {
      console.log("签合同");
      that.isContract()
    }
  },
  deposit() {
    const {
      order_id
    } = this.data;
    orderBuyDeposit(order_id).then(res => {
      if (res.trade_no) {
        my.tradePay({
          tradeNO: res.trade_no,
          success: (res) => {
            console.log(JSON.stringify(res));
            if (res.resultCode == 9000) {
              my.navigateTo({
                url: '../buyoutSuccess/buyoutSuccess?orderId=' + orderId
              });
            } else {
              my.showToast({
                type: 'fail',
                content: '支付失败，请稍后重试',
                // content: JSON.stringify(res),
                duration: 1000,
              });
            }
          }
        });
      }
    })
  },
  onAuth(){
    const {
      contract_type,
      order_id,
      goods_id,
      pay_type,
      sign_num
    } = this.data.goodsData
    my.navigateTo({
      url: '../../authentication/authentication?orderId=' + order_id + '&goodsId=' + goods_id + '&payType=' + pay_type +
        '&contractType=' + contract_type + '&signNum=' + sign_num
    })
  },
  cancelOrdera(){
    let that=this
    let {order_id}  =this.data.goodsData
    cancelOrder(order_id, function () {
      that.getData();
    })
  }
});